'use client';

import React, { useState, useEffect } from 'react';
import { 
  Row, 
  Col, 
  Card, 
  Statistic, 
  DatePicker, 
  Button, 
  Space,
  Spin,
  Typography
} from 'antd';
import { 
  UserOutlined, 
  ShoppingCartOutlined, 
  DollarCircleOutlined, 
  BarChartOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { Line, Column } from '@ant-design/plots';
import AdminLayout from '@/components/AdminLayout';

const { RangePicker } = DatePicker;
const { Title } = Typography;

// 模拟销售数据
const generateSalesData = () => {
  const data = [];
  const categories = ['阿拉斯加帝王蟹', '波士顿龙虾', '三文鱼', '金枪鱼', '扇贝'];
  
  for (let i = 0; i < 30; i++) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    
    data.push({
      date: date.toISOString().split('T')[0],
      sales: Math.floor(Math.random() * 10000) + 5000,
      orders: Math.floor(Math.random() * 100) + 50,
      category: categories[Math.floor(Math.random() * categories.length)]
    });
  }
  
  return data.reverse();
};

const AnalyticsPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [analyticsData, setAnalyticsData] = useState<any>({});
  const [salesData, setSalesData] = useState<any[]>([]);

  useEffect(() => {
    fetchAnalyticsData();
    setSalesData(generateSalesData());
  }, []);

  const fetchAnalyticsData = async () => {
    try {
      setLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setAnalyticsData({
        userStats: {
          totalUsers: 1245,
          newUsers: 45,
          activeUsers: 896,
        },
        orderStats: {
          totalOrders: 896,
          completedOrders: 756,
          revenue: 1234567.89,
        },
        productStats: {
          totalProducts: 156,
          bestSellingProduct: '阿拉斯加帝王蟹',
          lowStockProducts: 12,
        }
      });
    } catch (error) {
      console.error('获取分析数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 销售趋势图配置
  const salesTrendConfig = {
    data: salesData,
    xField: 'date',
    yField: 'sales',
    seriesField: 'category',
    smooth: true,
    point: {
      size: 3,
      shape: 'circle',
      style: {
        lineWidth: 1,
        fillOpacity: 1,
      },
    },
    tooltip: {
      formatter: (datum: any) => {
        return { name: datum.category, value: `¥${datum.sales.toLocaleString()}` };
      },
    },
    legend: {
      position: 'top' as const,
    },
  };

  // 订单量柱状图配置
  const orderVolumeConfig = {
    data: salesData,
    xField: 'date',
    yField: 'orders',
    seriesField: 'category',
    isGroup: true,
    columnStyle: {
      radius: [2, 2, 0, 0],
    },
    tooltip: {
      formatter: (datum: any) => {
        return { name: datum.category, value: `${datum.orders} 单` };
      },
    },
    legend: {
      position: 'top' as const,
    },
  };

  return (
    <AdminLayout 
      selectedKey="6" 
      breadcrumbItems={[{ title: '数据分析' }]}
    >
      <div style={{ padding: '24px' }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '24px' 
        }}>
          <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
            数据分析
          </h1>
          <Space>
            <RangePicker />
            <Button icon={<ReloadOutlined />} onClick={fetchAnalyticsData}>
              刷新
            </Button>
          </Space>
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: '50px' }}>
            <Spin size="large" />
          </div>
        ) : (
          <>
            {/* 用户统计 */}
            <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="总用户数"
                    value={analyticsData.userStats?.totalUsers || 0}
                    prefix={<UserOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="新增用户"
                    value={analyticsData.userStats?.newUsers || 0}
                    prefix={<UserOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="活跃用户"
                    value={analyticsData.userStats?.activeUsers || 0}
                    prefix={<UserOutlined />}
                  />
                </Card>
              </Col>
            </Row>

            {/* 订单统计 */}
            <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="总订单数"
                    value={analyticsData.orderStats?.totalOrders || 0}
                    prefix={<ShoppingCartOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="已完成订单"
                    value={analyticsData.orderStats?.completedOrders || 0}
                    prefix={<ShoppingCartOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="总收入"
                    value={analyticsData.orderStats?.revenue || 0}
                    prefix={<DollarCircleOutlined />}
                    precision={2}
                    formatter={(value: number) => `¥${value?.toLocaleString()}`}
                  />
                </Card>
              </Col>
            </Row>

            {/* 销售趋势图表 */}
            <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
              <Col span={24}>
                <Card>
                  <Title level={5} style={{ marginBottom: '20px' }}>销售趋势</Title>
                  <Line {...salesTrendConfig} />
                </Card>
              </Col>
            </Row>

            {/* 订单量图表 */}
            <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
              <Col span={24}>
                <Card>
                  <Title level={5} style={{ marginBottom: '20px' }}>订单量统计</Title>
                  <Column {...orderVolumeConfig} />
                </Card>
              </Col>
            </Row>

            {/* 产品统计 */}
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="产品总数"
                    value={analyticsData.productStats?.totalProducts || 0}
                    prefix={<BarChartOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="畅销产品"
                    value={analyticsData.productStats?.bestSellingProduct || '暂无数据'}
                    prefix={<BarChartOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={8}>
                <Card>
                  <Statistic
                    title="低库存产品"
                    value={analyticsData.productStats?.lowStockProducts || 0}
                    prefix={<BarChartOutlined />}
                  />
                </Card>
              </Col>
            </Row>
          </>
        )}
      </div>
    </AdminLayout>
  );
};

export default AnalyticsPage;